package com.tiantianyuegou.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.ProductDespAdapter;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.model.ProductImgeModel;
import com.tiantianyuegou.model.ProductSettingModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.MultipartEntity;
import com.tiantianyuegou.util.PictureUtil;
import com.tiantianyuegou.util.ToastUtilsCenter;
import com.tiantianyuegou.util.Tools;
import com.tiantianyuegou.view.NoScrollListView;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 商品描述
 * Created by ivany on 2016/1/20.
 */
public class ProductDespActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    private TextView mTxt_complete;
    private RelativeLayout mRelate_addPic;
    private NoScrollListView mLisView;
    private ArrayList<ProductImgeModel> mData;
    private ArrayList<String> mPicUrl;//用来存放图片路劲（传递用）
    private ProductDespAdapter mAdapter;

    private Dialog mAddDialog, mDeleteDialog;
    private String mDesp;
    private Bitmap mBitmap;
    private EditText mEt_desp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_desp);
        setTitle("商品描述");
       Tools.changeSystemBar(this);
        initViews();
    }

    @Override
    public void findViewByIds() {
        mRelate_addPic = (RelativeLayout) findViewById(R.id.product_desp_add);
        mTxt_complete = (TextView) findViewById(R.id.product_desp_complete);
        mLisView = (NoScrollListView) findViewById(R.id.product_desp_img_list);
        addHead();
    }

    private void addHead() {
        mEt_desp = new EditText(this);
        mEt_desp.setHint("添加图片和文字让你的商品看起来更诱人");
        mEt_desp.setBackgroundResource(R.color.md_grey_200);
        mEt_desp.setTextSize(14f);
        mEt_desp.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mDesp = s.toString();
            }
        });
        mLisView.addHeaderView(mEt_desp);
    }

    @Override
    public void initListener() {
        mLisView.setOnItemClickListener(this);
        mTxt_complete.setOnClickListener(this);
        mRelate_addPic.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mData = new ArrayList<>();
        mPicUrl = new ArrayList<>();
        mAdapter = new ProductDespAdapter(this);
        mLisView.setAdapter(mAdapter);
        Intent intent = getIntent();
        if (intent.hasExtra("desp")) {
            mDesp = getIntent().getStringExtra("desp");
            mEt_desp.setText(mDesp);
        }
        if (intent.hasExtra("picUrl")) {
            List<String> urls = (ArrayList<String>) intent.getSerializableExtra("picUrl");
            for (int i = 0; i < urls.size(); i++) {
                ProductImgeModel model = new ProductImgeModel();
                model.setUrl(urls.get(i));
                mData.add(model);
            }
            mAdapter.setData(mData);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        deleteDialog(position);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.product_desp_complete:
                if ((mDesp == null || "".equals(mDesp))&&(mData==null||mData.size()==0)) {
                   ToastUtilsCenter.makeText(this, "请输入商品描述", Toast.LENGTH_SHORT).show();
                } else {
                    mPicUrl.clear();
                    for (int i = 0; i < mData.size(); i++) {
                        mPicUrl.add(mData.get(i).getUrl());
                    }
                    Intent intent = new Intent();
                    intent.putExtra("desp", mDesp);
                    intent.putExtra("picList", mPicUrl);
                    setResult(Constant.EDIT_DESP_RESULT, intent);
                    finish();
                }
                break;
            case R.id.product_desp_add:
                addDialog();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            Intent intent = new Intent("com.android.camera.action.CROP");
            Uri data2 = null;
            if (data == null) {
                data2 = PictureUtil.getImageUri();
            } else {
                data2 = data.getData();
            }
            if (requestCode == Constant.MEDIA_CROP_REQUEST_CODE) {
                mBitmap = decodeUriAsBitmap(imageFilePath);// decode
                uploadBmp(mBitmap); //上传头像到服务器端
            } else if (requestCode == Constant.MEDIA_IMAGE_REQUEST_CODE) {
                if (data != null) {
                    imageFilePath = data.getData();
                    cropImageUri(imageFilePath, 200,200,
                            Constant.MEDIA_CROP_REQUEST_CODE);
                }
            } else if (requestCode == Constant.MEDIA_CAMERA_REQUEST_CODE) {
                cropImageUri(imageFilePath, 200, 200, Constant.MEDIA_CROP_REQUEST_CODE);
            } else if (requestCode == PictureUtil.PHOTO_PICKED_WITH_DATA) {
                intent.setDataAndType(data2, "image/*");
                intent.putExtra("crop", true);
                // 设置裁剪尺寸
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", 200);
                intent.putExtra("outputY", 200);
                intent.putExtra("return-data", true);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        PictureUtil.getImageCaiUri());
                startActivityForResult(intent,PictureUtil.PHOTO_CROP);
            } else if (requestCode == PictureUtil.PHOTO_CROP) {
                Bundle bundle = data.getExtras();
                Bitmap myBitmap = (Bitmap) bundle.get("data");
                mBitmap = PictureUtil.comp(myBitmap);

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(mBitmap, file);
                uploadBmp(mBitmap);
            }
            mAddDialog.dismiss();
        }
    }

    //删除
    private void deleteDialog(final int position) {
        View view = getLayoutInflater().inflate(R.layout.dialog_head, null);
        mDeleteDialog = new Dialog(this, R.style.transprentFrameWindowStyle);
        mDeleteDialog.setContentView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));
        Window window = mDeleteDialog.getWindow();
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        mDeleteDialog.onWindowAttributesChanged(wl);
        mDeleteDialog.setCanceledOnTouchOutside(true);

        Button dialog_photograph, dialog_photo, dialog_quit;
        dialog_photo = (Button) view.findViewById(R.id.dialog_photo);
        dialog_photo.setText("取消");
        dialog_photograph = (Button) view.findViewById(R.id.dialog_photograph);
        dialog_photograph.setText("删除");

        dialog_quit = (Button) view.findViewById(R.id.dialog_quit);
        dialog_quit.setVisibility(View.GONE);
        //删除
        dialog_photograph.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mData.remove(position - 1);
                mAdapter.setData(mData);
                mAdapter.notifyDataSetChanged();
                mDeleteDialog.dismiss();
            }
        });

        dialog_photo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mDeleteDialog.dismiss();
            }
        });
        mDeleteDialog.show();
    }

    private Uri imageFilePath;

    //添加
    private void addDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_head, null);
        mAddDialog = new Dialog(this, R.style.transprentFrameWindowStyle);
        mAddDialog.setContentView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));
        Window window = mAddDialog.getWindow();
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        mAddDialog.onWindowAttributesChanged(wl);
        mAddDialog.setCanceledOnTouchOutside(true);

        Button dialog_photograph, dialog_photo, dialog_quit;

        dialog_photograph = (Button) view.findViewById(R.id.dialog_photograph);
        dialog_photo = (Button) view.findViewById(R.id.dialog_photo);
        dialog_quit = (Button) view.findViewById(R.id.dialog_quit);

        /**
         * 系统相机
         */
        dialog_photograph.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 调用系统相机
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                ContentValues values = new ContentValues(3);
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                imageFilePath = ProductDespActivity.this.getContentResolver()
                        .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                values);

                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFilePath);
                startActivityForResult(intent, Constant.MEDIA_CAMERA_REQUEST_CODE);

            }
        });

        /**
         * 系统相册
         */
        dialog_photo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 调用系统相册
               PictureUtil.doPickPhotoFromGallery(ProductDespActivity.this);
            }
        });

        dialog_quit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mAddDialog.dismiss();
            }
        });
        mAddDialog.show();
    }


    private void uploadBmp(Bitmap b) {
        new UploadTask().execute(b);
    }

    private class UploadTask extends AsyncTask<Bitmap, String, String> {
       LoadingDialog loadingDialog = null;

        public UploadTask() {
            loadingDialog = new LoadingDialog(ProductDespActivity.this);
            loadingDialog.setMsg("正在上传图片");
            loadingDialog.show();
        }

        protected String doInBackground(Bitmap... bitmaps) {
            if (bitmaps[0] == null)
                return null;

            Bitmap bitmap = bitmaps[0];
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            InputStream in = new ByteArrayInputStream(stream.toByteArray());

            DefaultHttpClient httpclient = new DefaultHttpClient();
            ByteArrayOutputStream baos;
            try {
                HttpPost httppost = new HttpPost(ApiDefine.UPLOAD_PRODUCT_PIC); // server

                MultipartEntity reqEntity = new MultipartEntity();

                reqEntity.addPart("photo", System.currentTimeMillis() + ".jpg",
                        in);

                httppost.setEntity(reqEntity);

                System.out.println("requestLineInfo>>"
                        + httppost.getRequestLine());
                HttpResponse response = null;
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                try {
                    response = httpclient.execute(httppost);
                    if (response != null) {
                        StatusLine statusLine = response.getStatusLine();
                        System.out.println(statusLine.getStatusCode());
                        if (statusLine != null
                                && statusLine.getStatusCode() == HttpStatus.SC_OK) {
                            InputStream is = response.getEntity().getContent();
                            baos.reset();
                            for (int len = is.read(buffer); len != -1; len = is
                                    .read(buffer)) {
                                baos.write(buffer, 0, len);
                            }
                            System.out.println(baos.toString());
                        }
                    }

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (response != null)
                        System.out.println("responseInfo>>"
                                + response.getStatusLine().toString());
                } finally {

                }
            } finally {

            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return baos.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            loadingDialog.dismiss();
            uploadAvaterResult(result);
        }
    }

    /**
     * 解析是否上传头像成功
     */
    private void uploadAvaterResult(String resultJson) {
        try {
            JSONObject bean = new JSONObject(resultJson);
            String code = bean.getString("code");
            if ("100".equals(code)) {
                String result = bean.getString("result");
                mData.add(new ProductImgeModel(mBitmap, result));
                mAdapter.setData(mData);
                mAdapter.notifyDataSetChanged();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * bitmap 转换成字节
     */
    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * Uri转化成Bmp
     */
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver()
                    .openInputStream(uri));
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    /**
     * 裁剪图片
     */
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }
}
